package com.lzy.cloud.payment.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public final class StringUtil {

	public static final String UTF8 = "UTF-8";
	public static boolean isMobile(String phone) {
		String regExp = "^1([3|4|5|7|8])[0-9]{9}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phone);
		return m.find() ? false : true;
	}

	public static final boolean isNullOrEmpty(String value) {
		return value == null || value.length() == 0;
	}

	public static final String join(int[] val) {
		return join(val, ",");
	}

	public static final String join(int[] val, String separator) {
		if (val == null || val.length == 0) return null;

		String[] values = new String[val.length];
		for (int i = 0; i < val.length; i++) values[i] = String.valueOf(val[i]);
		
		return join(values,separator);
	}
	public static final String join(String[] value,String separator){
		if (value == null || value.length == 0) return null;
		StringBuffer str = new StringBuffer(512);
		str.append(value[0]);
		for (int i = 1; i < value.length; i++)
			str.append(separator).append(value[i]);
		
		return str.toString();
	}
	
	public static final String toJSON(Map<String,Object> map){
		JSONObject obj = new JSONObject();
		
		for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();) {
			String key = iter.next(),value = map.get(key).toString();
			obj.put(key, value);
		}
		
		return obj.toString();
	}
	

	public static final String dateFormat(Date date, String format) {
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}
	
	public static final String hexString(byte[] bytes) {
		if (bytes == null || bytes.length == 0)
			return "";
		StringBuffer hs = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			String s = Integer.toHexString(bytes[i] & 0xFF);
			if (s.length() < 2)
				hs.append(0);
			hs.append(s);
		}
		return hs.toString();
	}

	public static final String toSHA1(String value) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(value.getBytes());
			return hexString(digest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static final String toMD5(String value) {
		try {
			byte[] b = MessageDigest.getInstance("MD5").digest(value.getBytes(UTF8));
			return hexString(b);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 加密后解密  
	 public static String JM(String inStr) {  
	  char[] a = inStr.toCharArray();  
	  for (int i = 0; i < a.length; i++) {  
	   a[i] = (char) (a[i] ^ 't');  
	  }  
	  String k = new String(a);  
	  return k;  
	 }

	public static String md51(String str){
		return StringUtil.JM(StringUtil.JM(str));
	}


	public static String getBase64(String str) {
		try {
			return Base64.encodeBase64String(str.getBytes(UTF8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static String getFormBase64(String base64String){
		try {
			return new String(Base64.decodeBase64(base64String),UTF8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/** 
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i),value = params.get(key);
            
            // 拼接时，不包括最后一个&字符
            if (i == keys.size() - 1) {
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }
    /**
     * json字符串转化为map类型
     * @param jsonStr
     * @return
     */
    public static Map<String, Object> parseJSON2Map(String jsonStr){    
        Map<String, Object> map = new HashMap<String, Object>();    
        JSONObject json = JSONObject.fromObject(jsonStr);    
        for(Object k : json.keySet()){    
            Object v = json.get(k);     
            if(v instanceof JSONArray){    
                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();    
                Iterator<JSONObject> it = ((JSONArray)v).iterator();    
                while(it.hasNext()){    
                    JSONObject json2 = it.next();    
                    list.add(parseJSON2Map(json2.toString()));    
                }    
                map.put(k.toString(), list);    
            } else {    
                map.put(k.toString(), v);    
            }    
        }    
        return map;    
    }  

}
